/**
 * 小小的静态服务
 *  服务器：返回静态文件，返回数据
 *  mime模块自动获取文件的格式
 */
const fs = require('fs').promises;
const path = require('path');
const http = require('http');
const url = require('url');
const { createReadStream } = require('fs');
const mime = require('mime');

class StaticServer {
  constructor() {
    console.log(1);
  }
  async handleServer(req, res) {
    try {
      const { pathname } = url.parse(req.url, true);
      // console.log(pathname);
      let filePath = path.join(__dirname, pathname);
      // 处理接口请求
      if (req.method === 'GET' && pathname === '/api') {
        res.end('hello');
        return;
      }
      // 判断是不是文件夹
      let statObj = await fs.stat(filePath);

      if (statObj.isFile()) {
        res.setHeader(
          'Content-Type',
          mime.getType(filePath) + ';charset=utf-8'
        );
        createReadStream(filePath).pipe(res);
      } else {
        // 文件夹
        filePath = path.join(filePath, 'index.html');
        // 不存在这个文件夹，会报错，进入catch，后续的代码就不会走了
        await fs.access(filePath);
        res.setHeader('Content-Type', 'text/html;charset=utf-8');
        createReadStream(filePath).pipe(res);
      }
    } catch (error) {
      // console.log(error);
      this.sendError(error, req, res);
    }
  }
  sendError(error, req, res) {
    res.statusCode = 404;
    res.end('not found 404');
  }
  start(...args) {
    const server = http.createServer(this.handleServer.bind(this));
    server.listen(...args);
  }
}
const server = new StaticServer();
server.start(7000, () => {
  console.log('listen 7000');
});
